<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import { useBookingStore } from '@/stores/index.js'
import { useUserStore } from '@/stores/index.js'
import { formatTime, formatDate, diffDays } from '@/utils/formatTime'
import NewVisitorForm from '@/ComprehensivePackage/Booking/components/NewVisitorForm.vue'
import PaymentComponent from '@/components/PaymentComponent/PaymentComponent.vue'
import { userSubmitOrderService } from '@/apis/order'

const UserStore = useUserStore()
const BookingStore = useBookingStore()

// 获取表单组件实例
const newVisitorFormRef = ref(null)

// 预定的价格和规格信息
const bookingInfo = ref({})

// 控制日期选择组件的弹出
const isShow = ref(false)

// 控制新增出行人员弹出层组件的弹出
const isVisitorOpen = ref(false)

// 控制付款弹出层组件的弹出
const isPayOpen = ref(false)

// 用户选中的日期数据
const confirmDate = ref(null)

// 用户选中的出行开始日期(适用于酒店)
const travelStartDate = ref(null)

// 用户选中的出行结束日期(适用于酒店)
const travelEndDate = ref(null)

// 用户选择的数量
const quantity = ref(1)

// 提交订单后返回的订单号
const orderID = ref(null)

// 订单总价格
const totalPrice = computed(() => {
	const price =
		bookingInfo.value?.placeType === 'scenery'
			? bookingInfo.value?.ticket_price
			: bookingInfo.value?.placeType === 'hotel'
			? bookingInfo.value?.room_price * diffDays(travelStartDate.value, travelEndDate.value) || bookingInfo.value?.room_price
			: bookingInfo.value?.package_price
	return (price || 0) * (quantity.value || 1)
})

// 确定选择的日期
const onConfirmDate = (date) => {
	if (bookingInfo.value.placeType === 'hotel') {
		travelStartDate.value = date[0]
		travelEndDate.value = date[date.length - 1]
		confirmDate.value = formatDate(date[0]) + ' — ' + formatDate(date[date.length - 1])
	} else {
		confirmDate.value = formatDate(date[0])
	}
	isShow.value = false
}

// 新增出行人员组件弹出
const visitorOpen = () => {
	isVisitorOpen.value = true
}

// 新增出行人员组件关闭
const visitorClose = () => {
	isVisitorOpen.value = false
	newVisitorFormRef.value.clearFormData()
}

// 付款组件弹出
const payOpen = () => {
	isPayOpen.value = true
}

// 付款组件关闭
const payClose = () => {
	isPayOpen.value = false
	uni.reLaunch({
		url: '/UserCenterPackage/Orders/Orders?index=2'
	})
}

// 订单数据验证函数
const validateOrderData = () => {
	if (!confirmDate.value) {
		uni.showToast({
			icon: 'error',
			title: '请选择出行日期'
		})
		return false
	}

	if (!BookingStore.bookingData.visitors || BookingStore.bookingData.visitors.length === 0) {
		uni.showToast({
			icon: 'error',
			title: '请添加出行人'
		})
		return false
	}

	if (quantity.value > BookingStore.bookingData.visitors.length) {
		uni.showModal({
			content: '出行人数量不足，请添加出行人',
			showCancel: false, // 不显示取消按钮
			confirmText: '确定'
		})
		return false
	} else if (quantity.value < BookingStore.bookingData.visitors.length) {
		uni.showModal({
			content: '订单数量不足，请增加订单数量',
			showCancel: false, // 不显示取消按钮
			confirmText: '确定'
		})
		return false
	}

	return true
}

// 提交订单确认付款
const onClickPayment = async () => {
	// 验证订单数据
	if (!validateOrderData()) {
		return
	}

	// 需要提交的订单数据
	const orderData = {
		user_id: UserStore.UserInfoList.user_id,
		place_id: bookingInfo.value.placeID,
		order_type: bookingInfo.value.placeType,
		place_name: bookingInfo.value.placeName,
		product_type:
			bookingInfo.value.placeType === 'scenery'
				? bookingInfo.value.ticket_type
				: bookingInfo.value.placeType === 'hotel'
				? bookingInfo.value.room_type
				: bookingInfo.value.package_name,
		price:
			bookingInfo.value.placeType === 'scenery'
				? bookingInfo.value.ticket_price
				: bookingInfo.value.placeType === 'hotel'
				? bookingInfo.value.room_price
				: bookingInfo.value.package_price,
		quantity: quantity.value,
		description: bookingInfo.value.description,
		total_amount: totalPrice.value,
		travel_start_date: bookingInfo.value.placeType === 'hotel' ? travelStartDate.value : formatTime(confirmDate.value),
		travel_end_date: bookingInfo.value.placeType === 'hotel' ? travelEndDate.value : formatTime(confirmDate.value),
		people: bookingInfo.value.visitors
	}

	try {
		// 提交订单数据
		const res = await userSubmitOrderService(orderData)
		orderID.value = res.data

		// 打开付款组件
		payOpen()
	} catch (error) {
		uni.showToast({
			icon: 'error',
			title: '订单提交失败'
		})
	}
}

onLoad(() => {
	// 从Pinia中获取预定信息数据
	bookingInfo.value = BookingStore.bookingData
})
</script>

<template>
	<view class="container">
		<view class="place">
			<view class="name">
				{{ bookingInfo.placeName }}
			</view>

			<view class="introduce">
				{{ bookingInfo.description }}
			</view>

			<view class="booking-date">
				{{ confirmDate }}
			</view>
		</view>

		<view class="price">
			<view class="type">
				{{ bookingInfo.placeType === 'scenery' ? bookingInfo.ticket_type : bookingInfo.placeType === 'hotel' ? bookingInfo.room_type : bookingInfo.package_name }}
			</view>
			<view class="price-detail">
				<view class="money">￥</view>
				<view class="number">
					{{ bookingInfo?.placeType === 'scenery' ? bookingInfo?.ticket_price : bookingInfo?.placeType === 'hotel' ? bookingInfo?.room_price : bookingInfo?.package_price }}
				</view>
			</view>
			<up-number-box color="#ffffff" bgColor="#f56c6c" iconStyle="color: #fff" v-model="quantity"></up-number-box>
		</view>

		<view class="date">
			<view class="text">日期选择</view>
			<up-button @tap="isShow = true" type="primary" color="#f56c6c" :text="confirmDate ? confirmDate : '请选择日期'"></up-button>
			<view class="choose-date">
				<up-calendar
					:startText="bookingInfo.placeType === 'hotel' ? '住店' : ''"
					:endText="bookingInfo.placeType === 'hotel' ? '离店' : ''"
					:confirmDisabledText="bookingInfo.placeType === 'hotel' ? '请选择离店日期' : ''"
					color="#f56c6c"
					:show="isShow"
					@confirm="onConfirmDate"
					@close="isShow = false"
					closeOnClickOverlay
					:mode="bookingInfo.placeType === 'hotel' ? 'range' : 'single'"
				></up-calendar>
			</view>
		</view>

		<view class="people">
			<view class="title">
				{{ bookingInfo.placeType === 'scenery' ? '游客信息' : bookingInfo.placeType === 'hotel' ? '入住信息' : '顾客信息' }}
			</view>
			<view class="visitors">
				<view class="visitor-list">
					<view
						class="visitor-item"
						v-if="BookingStore.bookingData.visitors && BookingStore.bookingData.visitors.length > 0"
						v-for="(item, index) in BookingStore.bookingData.visitors"
						:key="index"
					>
						{{ item.name }}
					</view>
				</view>

				<view class="icon" @tap="visitorOpen">
					<text class="iconfont icon-jia"></text>
				</view>
			</view>
		</view>

		<!-- 新增出行人员 -->
		<up-popup :show="isVisitorOpen" :round="10" mode="bottom" closeable closeOnClickOverlay @close="visitorClose" @open="visitorOpen">
			<NewVisitorForm ref="newVisitorFormRef" @closeProp="visitorClose"></NewVisitorForm>
		</up-popup>

		<view class="bottom">
			<view class="total-price">
				<view class="money">￥</view>
				<view class="number">{{ totalPrice.toFixed(2) }}</view>
			</view>
			<view class="pay-btn" @tap="onClickPayment">去付款</view>
		</view>

		<!-- 提交订单并付款 -->
		<up-popup :show="isPayOpen" :round="10" mode="bottom" closeable closeOnClickOverlay @close="payClose" @open="payOpen">
			<PaymentComponent
				v-if="bookingInfo"
				@closePayProp="payClose"
				:totalPrice="totalPrice || 0"
				:orderID="orderID || 0"
				:userID="UserStore.UserInfoList.user_id || 0"
			></PaymentComponent>
		</up-popup>
	</view>
</template>

<style lang="scss" scoped>
.container {
	@mixin common-card {
		background-color: #fff;
		border-radius: 30rpx;
		margin: 20rpx;
		padding: 40rpx;
	}

	@mixin common-price {
		display: flex;
		justify-content: flex-end;
		align-items: baseline;

		.money {
			color: #fb4223;
			font-size: 30rpx;
		}

		.number {
			font-size: 45rpx;
			font-weight: bold;
			color: #fb4223;
		}
	}

	.place {
		@include common-card;

		.name {
			font-size: 40rpx;
			font-weight: bold;
			padding-bottom: 25rpx;
		}

		.introduce {
			padding-bottom: 20rpx;
		}
	}

	.price {
		@include common-card;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.price-detail {
			@include common-price;
		}
	}

	.date {
		@include common-card;
		display: flex;
		flex-direction: column;
		align-items: flex-start;

		.text {
			font-size: 35rpx;
			padding-bottom: 30rpx;
		}
	}

	.people {
		@include common-card;

		.title {
			font-size: 35rpx;
			padding-bottom: 30rpx;
		}

		.visitors {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			align-items: center;

			.visitor-list {
				width: 100%;
				padding-bottom: 40rpx;
				display: grid;
				grid-template-columns: repeat(3, 1fr);
				gap: 20rpx;

				.visitor-item {
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 20rpx 30rpx;
					background-color: #f78989;
					border: 4rpx solid #f56c6c;
					border-radius: 10rpx;
					color: #fff;
				}
			}

			.icon {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 85rpx;
				height: 85rpx;
				border-radius: 50%;
				background-color: #f56c6c;
				color: #fff;
			}
		}
	}

	.bottom {
		width: 100%;
		height: 200rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 999;
		padding: 40rpx;
		display: flex;
		background-color: #ffffff;
		justify-content: space-between;
		align-items: center;

		.total-price {
			@include common-price;
		}

		.pay-btn {
			width: 40%;
			border-radius: 999rpx;
			background-color: #fb4223;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 15rpx 40rpx;
			font-size: 40rpx;
			color: #fff;
			font-weight: bold;
		}
	}
}
</style>
